package com.aaa.mysecurity.service;



import com.aaa.mysecurity.dao.PermissionDao;
import com.aaa.mysecurity.dao.UserDao;
import com.aaa.mysecurity.entity.MyUser;
import com.aaa.mysecurity.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ：ludi（206913808@qq.com）
 * @date ：Created in 2022/11/1 17:01
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class MyService implements UserDetailsService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUser = userDao.selectByUsername(username);
        if (myUser !=null){
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        List<Permission> all = permissionDao.findAllById(myUser.getUserid());
        for (Permission permission : all) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getPercode());
            authorities.add(simpleGrantedAuthority);
        }
            User user = new User(username, myUser.getUserpwd(), authorities);
            return user;
        }
        return null;
    }
}